package com.tsk.state.test;

import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author: 黄嘉振
 * @create: 2023/5/25 14:18
 * @description:
 **/
@Component
public class MyStateMachinePersist implements StateMachinePersist<OrderStatus, OrderStatusChangeEvent, String> {
    private final HashMap<String, StateMachineContext<OrderStatus, OrderStatusChangeEvent>> contexts = new HashMap<>();

    @Override
    public void write(StateMachineContext<OrderStatus, OrderStatusChangeEvent> context, String contextObj) throws Exception {
        // 自行处理持久层逻辑
        System.out.println("write context: " + context);
        System.out.println("write contextObj: " + contextObj);
        contexts.put(contextObj, context);
        System.out.println("write contexts map : " + contexts);
    }

    @Override
    public StateMachineContext<OrderStatus, OrderStatusChangeEvent> read(String contextObj) throws Exception {
        // 后续修改为查询数据库获取订单状态，并返回
        System.out.println("read contextObj: " + contextObj);
        StateMachineContext<OrderStatus, OrderStatusChangeEvent> context = contexts.get(contextObj);
        System.out.println("read context: " + context);
        System.out.println("read contexts map : " + contexts);
        if (contextObj.equals("1234")) {
            return new DefaultStateMachineContext<>(OrderStatus.FINISH, null, null, null);
        }
        return context;
    }
}
